package com.huawei.codearts.tools.validated;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.Map;

public class CustomValidator implements ConstraintValidator<ValidParams, Map<String, Object>> {

    @Override
    public void initialize(ValidParams constraintAnnotation) {
        // 可以在这里初始化注解的属性值
    }

    @Override
    public boolean isValid(Map<String, Object> params, ConstraintValidatorContext context) {
        try {
            if (params == null || params.isEmpty()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("参数不能为空")
                        .addPropertyNode("params")
                        .addConstraintViolation();
                return false;
            }

            // 在这里实现验证逻辑
            String id = (String) params.get("id");
            String username = (String) params.get("username");
            Integer age = params.get("age") != null && !params.get("age").equals("") ? Integer.parseInt((String) params.get("age")) : null;

            if (id == null || id.isEmpty()) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("ID不能为空")
                        .addPropertyNode("id")
                        .addConstraintViolation();
                return false;
            }

            if (username == null || username.length() < 3 || username.length() > 20) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("用户名长度必须在3到20个字符之间")
                        .addPropertyNode("username")
                        .addConstraintViolation();
                return false;
            }

            if (age == null || age < 18 || age > 65) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("年龄必须在18到65岁之间")
                        .addPropertyNode("age")
                        .addConstraintViolation();
                return false;
            }

            return true;
        } catch (Exception e) {
            System.err.println("Validation error: " + e.getMessage());
            return false;
        }
    }
}
